<template>
	<view :class="'relative ' + extraClass">
		<view @click="show">
			<text class='color-main mr-2'>{{curText}}</text>
			<text class='iconfont icon-arrow-down color-secondary-1'></text>
		</view>
		<view class='absolute right-0 top-full bg-white b-solid-thin b-color-1 mt-1 rounded-n overflow-hidden z-30' v-show="visible">
			<view v-for="(el,i) in data" class='py-1 px-3 b-bottom-solid-thin b-color-1' 
				:key="el.value"
				:style="{'border-bottom-width': i === data.length - 1 ? 0 : '1px'}"
				:class="{'dropdown-item-selected': el.value === curValue}"
				hover-class="dropdown-item-active" hover-start-time="0" hover-stay-time="10"
				@click="clickItem(el)"
			>
				<text class='color-main'>{{el.text}}</text>
			</view>
		</view>
		<view class='fixed inset-0 z-20' v-show="visible" @click="hide"></view>
	</view>
</template>

<script>
	import { ref,computed } from "vue";
	export default {
		name: "Dropdown",
		props: {
			data: Array,
			extraClass: String,
			initValue: [String,Number]
		},
		setup(props,ctx){
			const visible = ref(false);
			const curValue = ref(props.initValue);
			const curText = computed(() => {
				for(let i=0;i<props.data.length;i++){
					const item = props.data[i];
					if(item.value === curValue.value || item === curValue.value){
						return item.text || item;
					}
				}
				return "";
			});
			function toggle(){
				visible.value = !visible.value;
			}
			function clickItem(el){
				curValue.value = el.value;
				ctx.emit('select',el);
				visible.value = false;
			}
			function hide(){
				visible.value = false;
			}
			function show(){
				visible.value = true;
			}
			return {
				visible,
				toggle,
				clickItem,
				curValue,
				curText,
				hide,
				show
			};
		}
	}
</script>

<style lang="scss">
	.dropdown-item-active,.dropdown-item-selected{
		background-color: $color-primary;
		.color-main{
			color: #FFFFFF;
		}
	}
</style>
